define(function(require, exports, module){

	require('{component}popup/popup.css');
	var popup = require('{component}popup/popup'),
		container = require("{component}container/container"),
		tplContainer = require("{view}container.tpl"),
		mId = 'search',
		g_data,
		tpl = require("{view}search.tpl"),
	view = {

		template: _.template(tpl),
		templateContainer: _.template(tplContainer),

		render:function(){
			var parameter = share.getParameter(),
				q = decodeURI(parameter.q);
			window.scroll(0,0);
			
			if(q==undefined || $('#'+mId).attr('q') != q){
				this.ajaxSearch(q);

			}else{
				share.showPage(mId);
			}
			this.reload();
		},
		reload:function(){
			var dom = $('#'+mId);
			
			container.reload(mId);
		},
		bindEvt:function(){
			var tthis = this;
			var dom = $("#"+mId);

			dom.find('.tabs li').on('tap',function(){
				var index = $(this).index();
				share.tabSwitch(dom,index);
			});

			dom.find('.body_song li').on('tap',function(){
				var songid = $(this).attr('songid');
				util.setLocalStorage('play_list',g_data);
				window.location.href = '#play?songid='+songid;
			});

			dom.find('.body_artist li').on('tap',function(){
				var tinguid = $(this).attr('tinguid');
				window.location.href = '#singerSongList?tinguid='+tinguid;

			});

			dom.find('li .ico_more').on('tap',function(e){
				var songid = $(this).parents('li').attr('songid');
				e.stopPropagation();
				popup.show({type:'more',songid:songid,li:['recommended']});
			});

		},
		
		ajaxSearch:function(val){
			share.loading();
			var tthis = this,dom=$('#'+mId);
			$.ajax(share.ajax({
				url: apiUrl,
				data:{method:'baidu.ting.search.catalogSug',query:val},
				success:function(data){
					console.log(data)
					g_data = data;

					data.song   || (data.song = '');
					data.artist || (data.artist = '');
					data.album  || (data.album = '');

					dom.remove();
					$("body").append(tthis.template(data));
					share.container(mId,container,tthis.templateContainer,'top');
					$('#'+mId).attr({'q':val})
					tthis.bindEvt();
					tthis.reload();
					share.showPage(mId);
				}
			}))
		},
	};

	view.ajaxBool = true;
	view.userNav = false;
	module.exports =  view;
});

